<template>
  <div>
    <el-page-header title="返回" content="分类管理" @back="$router.go(-1)" />

    <el-row style="margin-top: 20px;">
      <el-col :span="8">
        <el-button type="primary" @click="showAddCategoryDialog">添加分类</el-button>
      </el-col>
    </el-row>

    <el-table :data="categories" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="showEditCategoryDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteCategory(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <CategoryForm
      v-model="showCategoryDialog"
      :initial-values="currentCategory"
      @submit="handleCategorySubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import categoriesApi from '@/api/categories'
import CategoryForm from '@/components/CategoryForm.vue'

interface Category {
  id?: number;
  name: string;
}

const categories = ref<Category[]>([])
const showCategoryDialog = ref(false)
const currentCategory = ref<Category>({ name: '' })

const loadCategories = async () => {
  try {
    const response = await categoriesApi.getCategories()
    categories.value = response.data
  } catch (error) {
    ElMessage.error('加载分类失败')
  }
}

const showAddCategoryDialog = () => {
  currentCategory.value = { name: '' }
  showCategoryDialog.value = true
}

const showEditCategoryDialog = (category: Category) => {
  currentCategory.value = { ...category }
  showCategoryDialog.value = true
}

const handleCategorySubmit = async (formData: Category) => {
  try {
    if (formData.id) {
      // 编辑分类
      await categoriesApi.updateCategory(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      // 添加分类
      await categoriesApi.createCategory(formData)
      ElMessage.success('创建成功')
    }
    await loadCategories()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteCategory = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个分类吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await categoriesApi.deleteCategory(id)
    ElMessage.success('删除成功')
    await loadCategories()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  loadCategories()
})
</script>